/*
 * @Author: modefy
 * @Date: 2023-04-26 17:10:32
 * @LastEditors: modefy
 * @LastEditTime: 2023-04-26 17:13:01
 * @Description: Description
 */
package com.example.learn.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.learn.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 创建一个 token 拦截器.
 * 需要继承 HandlerInterceptorAdapter,并且声明为spring的组件
 *
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {


    // 重写 前置拦截方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

//        放行嗅探，预检
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
//            System.out.println("Method:OPTIONS");
            return true;
        }
//        if(true){
//            return true;
//        }

        Map<String, String> map = new HashMap<>();
        // 1、从请求头中获取token
        String token = request.getHeader("token");
        try {
            JWTUtils.vertify(token);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "无效签名！");
        }catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期！");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token算法不一致！");
        }catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效！");
        }
        map.put("code", "0");
//        将map 转为json  jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}